import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home'
import Login from '@/views/Login'
import Receipt from '@/views/Receipt'
import Distribution from '@/views/Distribution'
import Donor from '@/views/Donor'
import Donee from '@/views/Donee'
import Chart from '@/views/Chart'
import Register from '@/views/Register'
import NotFound from '@/views/NotFound'
import LoginPage from '@/views/LoginPage'
import Title from '@/views/Title'

Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect: '/home/receipt',
    children: [{
        path: 'receipt',
        name: 'Receipt',
        component: Receipt,
        meta: {
          requireAuth: true,
        },
      },
      {
        path: 'distribution',
        name: 'distribution',
        component: Distribution,
        meta: {
          requireAuth: true,
        },
      },
      {
        path: 'donor',
        name: 'donor',
        component: Donor,
        meta: {
          requireAuth: true,
        },
      },
      {
        path: 'donee',
        name: 'donee',
        component: Donee,
        meta: {
          requireAuth: true,
        },
      },
      {
        path: 'chart',
        name: 'chart',
        component: Chart,
        meta: {
          requireAuth: true,
        },
      }
    ]
  },
  {
    path: '/loginPage',
    name: 'LoginPage',
    component: LoginPage,
    redirect: '/LoginPage/title',
    children: [{
        path: 'title',
        name: 'Title',
        component: Title
      },
      {
        path: 'login',
        name: 'Login',
        component: Login
      },
      {
        path: 'register',
        name: 'Register',
        component: Register
      }
    ]
  },
  {
    path: '*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // console.log(to.meta.requireAuth);
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    // console.log('need');
    if (localStorage.getItem('userData')) { // 通过localStorage获取当前的userData是否存在
      next();
    } else {
      next({
        path: '/loginPage'
      })
    }
  } else {
    next();
  }
});

export default router